
// http://125.94.106.113:81/
// let BASE_URL = 'https://talk.shuyeit.com:22301/api'
let BASE_URL = 'https://www.aiplxt.cn:82/api'

export function setBaseURL(baseURL) {
  BASE_URL = baseURL || ''
}

export function getBaseURL() {
  if (BASE_URL) return BASE_URL
  try {
    const storageBase = uni.getStorageSync('BASE_URL')
    return storageBase || ''
  } catch (_) {
    return ''
  }
}

function buildHeaders(extra) {
  const headers = {}
  if (extra) {
    for (const key in extra) headers[key] = extra[key]
  }
  // token 注入
  try {
    const token = uni.getStorageSync('token')
    if (token) headers['Authorization'] = `${token}`
  } catch (_) {}
  return headers
}

export function uploadFile(options) {
  const {
    filePath,
    formData,
    header,
    showLoading = false,
    onProgress
  } = options

  const finalURL = getBaseURL() + '/upload/file'
  const finalHeaders = buildHeaders(header)

  return new Promise((resolve, reject) => {
    if (showLoading) {
      uni.showLoading({ title: '加载中', mask: true })
    }

    const uploadTask = uni.uploadFile({
      url: finalURL,
      header: finalHeaders,
      name: 'files',
      filePath,
      formData,
      success: (res) => {
        const status = res.statusCode || 0
        const respData = JSON.parse(res.data)
        if (status === 200 && respData.code === 200) {
          resolve(respData.data)
          return
        }
      },
      fail: (err) => {
        uni.showToast({ title: '上传失败，请稍后重试-1', icon: 'none' })
        reject({ message: '上传失败，请稍后重试' })
      },
      complete: () => {
        if (showLoading) {
          uni.hideLoading()
        }
      }
    })
    uploadTask.onProgressUpdate((res) => {
      if (onProgress && typeof onProgress === 'function') {
        onProgress({
          progress: res.progress, // 上传进度百分比 0-100
          totalBytesSent: res.totalBytesSent, // 已经上传的数据长度
          totalBytesExpectedToSend: res.totalBytesExpectedToSend // 预期需要上传的数据长度
        })
      }
		});
  })
}


